﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web.Mail;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Ext.Net;
using Sio.Mdm.Client;
using Sio.Mdm.BF.Administracija;
using Sio.Mdm.Entities;
using Sio.Mdm.Types.Database;
using System.Collections.Generic;
using Sio.Mdm.Utils;
using Sio.Mdm.Types;

namespace Sio.Mdm.Web
{
    public partial class Login : Controls.Login
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Verzija.Text = String.Format("Sio.Mdm {0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
            if (!IsPostBack && !X.IsAjaxRequest)
            {
                if (Request.QueryString["guid"] != null)
                {
                    var auth = ServiceFactory.GetService<IPozabljenoGesloService>();
                    Sio.Mdm.Types.Result error;
                    string guid = Request.QueryString["guid"];
                    //veljaven guid
                    error = auth.PreveriGuid(guid);
                    if (error == null)
                        this.WPonastaviGeslo.Show();
                    else
                    {
                        // e.ErrorMessage = error.ToString();
                        X.Msg.Show(new MessageBoxConfig
                        {
                            Title = "Napaka",
                            Message = error.Message.ToString(),
                            Buttons = MessageBox.Button.OK,
                            Icon = MessageBox.Icon.ERROR
                        });
                    }
                }
#if DEBUG
                // for debug purposes auto-fill authentication data
                UserName.Text = "root";
                Password.Text = "root";
                Organizacija.SelectedIndex = 0;
                // by Jure
#endif
                //organizacije
                EntityCollection<Sio.Mdm.Types.Database.Organizacija> organizacije = new EntityCollection<Sio.Mdm.Types.Database.Organizacija>(new Filter<Sio.Mdm.Types.Database.Organizacija>().Where(r => (r.OrganizacijaId != null) && (r.Aktivno == true)));
                var tmpArray = (from p in organizacije select new Object[2] { p.OrganizacijaId, p.Naziv }).ToArray();
                this.StoreOrganizacije.DataSource = tmpArray;
                this.StoreOrganizacije.DataBind();
            }
        }

        protected void LoginClick(object sender, DirectEventArgs e)
        {
            //FormsAuthentication.SetAuthCookie(UserName.Text, false);
            //ExtNet.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text, false));


            var auth = ServiceFactory.GetService<IAvtorizacijaService>();
            Sio.Mdm.Types.Session session;
            Sio.Mdm.Types.Result error;

            error = auth.Login(UserName.Text, Password.Text, Int32.Parse(Organizacija.SelectedItem.Value), out session);
            if (error == null)
            {
                Logger.WriteInformation("Adding BL session to web session");
                Session["__session"] = session;
                SessionFactory.RegisterProvider(new Base.SessionProvider());
                //test za security tokene
                //IList<ZetoniUporabnika> tokens = new List<ZetoniUporabnika>();
                //var res = auth.SecurityTokens(session, ref tokens);
                //
                FormsAuthentication.SetAuthCookie(UserName.Text, false);
                //RedirectFromLogin(UserName.Text);
                RedirectFromTipVlogeId(session.TipVlogeId);
                //ExtNet.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text, false));
                //Response.Redirect("Default.aspx");
            }
            else
            {
                e.Success = false;
                e.ErrorMessage = error.ToString();
            }

        }

        protected void SendLogin(object sender, DirectEventArgs e)
        {
            var auth = ServiceFactory.GetService<IPozabljenoGesloService>();
            Sio.Mdm.Types.Result error = null;

            if (String.IsNullOrEmpty(this.OrganizacijaPG.Value as string))
            {
                e.Success = false;
                e.ErrorMessage = "Izberite organizacijo.";
            }
            else
            {
                error = auth.PozabljenoGeslo(this.tfUporabniskoIme.Text, this.tfEmail.Text, Convert.ToInt32(this.OrganizacijaPG.Value));
                if (error == null)
                {
                  string obvestilo = "";
                  if (!String.IsNullOrEmpty(this.tfEmail.Text))
                  {
                    obvestilo = "Na naslov " + this.tfEmail.Text + " je bila poslana elektronska pošta za ponastavitev gesla.";
                  }
                  else
                  {
                    obvestilo = "Na naslov od " + this.tfUporabniskoIme.Text + " je bila poslana elektronska pošta za ponastavitev gesla.";
                  }
                  X.Msg.Show(new MessageBoxConfig
                  {
                    Message = obvestilo,
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.INFO
                  });
                  this.WPozabljenoGeslo.Hide();
                }
                else
                {
                    e.Success = false;
                    e.ErrorMessage = error.Message.ToString();
                }
            }
        }
        protected void PonastaviGeslo(object sender, DirectEventArgs e)
        {
            var auth = ServiceFactory.GetService<IPozabljenoGesloService>();
            string guid = Request.QueryString["guid"];
            //LOCAL_ADDR, REMOTE_ADDR
            var error = auth.PonastaviGeslo(guid, this.tfNovoGeslo.Text, this.tfPotrdiGeslo.Text, Request.ServerVariables["REMOTE_HOST"].ToString());
            if (error == null)
                this.WPonastaviGeslo.Hide();
            else
            {
                e.Success = false;
                e.ErrorMessage = error.Message.ToString();
            }
        }
    }
}
